package com.yuanhua.sim.netty.decoder;

import com.alibaba.fastjson.JSON;
import com.yuanhua.core.base.entity.BaseBean;
import com.yuanhua.sim.netty.utils.MapUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;
import org.openjdk.jol.vm.VM;

import java.util.List;

/**
 * 解码
 * @author songguoxiang
 * @date: 2022/8/1 16:34
 */
@Slf4j
public class MyDecoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) {
        log.info("数据解码：{}, 对象地址: {}, 数据还可以写吗:{}", byteBuf, VM.current().addressOf(byteBuf), channelHandlerContext.channel().isWritable());
        //1.根据协议取出数据
        //标识符
        int tag=byteBuf.readInt();
        //获取指令
        byte code=byteBuf.readByte();
        //获取数据长度
        int len=byteBuf.readInt();


        int i = byteBuf.readableBytes();
        if (i < len) {
            System.out.println("当前可读数据不够，继续等待。。");
            return;
        }else {
            byte[] bytes=new byte[len];
            byteBuf.readBytes(bytes);
            //2.根据code获取类型
            Class<? extends BaseBean> c= MapUtils.getBean(code);
            //3.反序列化
            BaseBean baseBean= JSON.parseObject(bytes,c);

            list.add(baseBean);
        }

    }
}